import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';

///截图
Future<Uint8List?> screenShot({required GlobalKey globalKey, double pixelRatio = 0}) async {
  if (null != globalKey.currentContext) {
    try {
      RenderObject? boundary = globalKey.currentContext?.findRenderObject();
      if (0 == pixelRatio) {
        pixelRatio = window.devicePixelRatio;
      }
      if (boundary is RenderRepaintBoundary) {
        var image = await boundary.toImage(pixelRatio: pixelRatio);
        ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
        if (null != byteData) {
          Uint8List pngBytes = byteData.buffer.asUint8List();
          return pngBytes;
        }
      }
    } catch (e) {
      //
    }
  }
  return null;
}

Future<Uint8List?> captureScreenshot({required GlobalKey globalKey}) async {
  try {
    if (globalKey.currentContext != null) {
      if (globalKey.currentContext!.findRenderObject() != null) {
        RenderObject boundary = globalKey.currentContext!.findRenderObject()!;
        RenderRepaintBoundary repaintBoundary = boundary as RenderRepaintBoundary;

        ui.Image image = await repaintBoundary.toImage();

        ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
        if (byteData != null) {
          Uint8List? pngBytes = byteData.buffer.asUint8List();
          return pngBytes;
          final directory = await getApplicationDocumentsDirectory();
          final imagePath = '${directory.path}/screenshot.png';
          File imageFile = File(imagePath);
          await imageFile.writeAsBytes(pngBytes);
          print(imageFile.path);
          // 在这里可以用imageFile.path处理截图的路径，例如上传给服务器
        }
      }
    }
  } catch (e) {
    print('error: $e');
  }
  return null;
}
